<template>
  <div class="animate-clock"><!-- <p>{{days}}{{hours}}{{minites}}{{seconds}}</p> -->
    <animate-card :val="days" :size="16" :self-disabled="disabled" />
    <span>{{$t('天')}}</span>
    <animate-card :val="hours" :size="16" :self-disabled="disabled" />
    <span>{{$t('时')}}</span>
    <animate-card :val="minites" :size="16" :self-disabled="disabled" />
    <span>{{$t('分')}}</span>
    <animate-card :val="seconds" :size="16" :self-disabled="disabled" />
    <span>{{$t('秒')}}</span>
  </div>
</template>
<script>
import animateCard from './animate-card.vue'

export default {
  components: { animateCard },
  props: {
    terminalTime: Number || String
  },
  data () {
    return {
      days: ['0', '0'],
      hours: ['0', '0'],
      minites: ['0', '0'],
      seconds: ['0', '0'],
      setIntVal: null,
      disabled: false,
      terminalTimeNow: this.terminalTime
    }
  },
  watch: {
    terminalTime: {
      handler (newdata) {
        // 先调用一次
        this.handStopTime()
        if (newdata) {
          this.updateClock()
          // 箭头函数不修改当前作用域下的 this 指向
          this.setIntVal = setInterval(() => {
            this.terminalTimeNow -= 1000
            this.updateClock(this.terminalTimeNow)
          }, 1000)
        }
      },
      immediate: true
    }
  },
  beforeDestroy () {
    if (this.setIntVal) {
      clearInterval(this.setIntVal) // 在Vue实例销毁前，清除我们的定时器
    }
  },
  methods: {
    /** 更新计时器
     * @result void
     */
    updateClock (time) {
      let stopTime = time
      // 终止逻辑
      if (stopTime && stopTime < 1) {
        this.$emit('overTime')
        this.handStopTime()
        return false
      } else if (!stopTime) {
        return false
      }
      // 计算 日、时、分、秒
      let days = parseInt(stopTime / (24 * 60 * 60 * 1000))
      let hours = parseInt((stopTime - 24 * 60 * 60 * 1000 * days) / (60 * 60 * 1000))
      let minites = parseInt((stopTime - 24 * 60 * 60 * 1000 * days - 60 * 60 * 1000 * hours) / (60 * 1000))
      let seconds = parseInt((stopTime - 24 * 60 * 60 * 1000 * days - 60 * 60 * 1000 * hours - 60 * 1000 * minites) / 1000)
      // 更新 data
      this.days = this.toStringAndUnshiftZero(days)
      this.hours = this.toStringAndUnshiftZero(hours)
      this.minites = this.toStringAndUnshiftZero(minites)
      this.seconds = this.toStringAndUnshiftZero(seconds)
    },
    /**
     * 转化数字为数组，并在 头部填充 0
     * @params num: numnber
     * @result string[]
    */
    toStringAndUnshiftZero (num) {
      const val = num.toString().split('')
      if (num < 10) {
        val.unshift('0')
      }
      return val
    },
    handStopTime () {
      clearInterval(this.setIntVal)
      this.setIntVal = null
      // 计时器 清零
      this.days = this.hours = this.minites = this.seconds = ['0', '0']
    }
  }
}
</script>
<style lang="scss" scoped>
.animate-clock {
  width: 100%;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  padding: 40px 0;
}
</style>
